import logging
import time
import subprocess
import threading
import json
from service.device import device_manager
from service.device import device_actor
from service.device.device_actor import DeviceActor

_alive=True

STARTUP_INFO_NO_WIN=subprocess.STARTUPINFO()
STARTUP_INFO_NO_WIN.dwFlags=subprocess.STARTF_USESHOWWINDOW
STARTUP_INFO_NO_WIN.wShowWindow=subprocess.SW_HIDE

def release():
    global _alive
    _alive = False

def init():
    thread_LoopCheckDevices = threading.Thread(target=loopCheckDevices)
    thread_LoopCheckDevices.start()
    logging.info("设备变动开始监听")

def loopCheckDevices():
    while _alive:
        try:
            out_bytes = subprocess.check_output(['adb','devices'],startupinfo=STARTUP_INFO_NO_WIN)
            out_text = out_bytes.decode('utf-8')
            deviceSet = set()
            for ts in out_text.splitlines()[1:]:
                if len(ts)>0:
                    dname = ts.split("\t")[0]
                    deviceSet.add(dname)
            existDeviceMap = device_manager.getDeviceActorMap()
            for dname in deviceSet:
                if dname not in existDeviceMap: #新增
                    logging.info("发现新增设备 %s" %(dname,))
                    device_manager.addDeviceActor(dname)
                else:
                    existDevice: DeviceActor = existDeviceMap[dname]
                    if existDevice.state == device_actor.CONS.STATE_UNLINE: 
                        logging.info("发现重连设备")
                        existDevice.connect()
                    elif existDevice.state == device_actor.CONS.STATE_UNCONNECT: 
                        logging.info("发现未连接设备")
                        existDevice.connect()

            for existDeviceName,existDevice in existDeviceMap.items() :
                if existDeviceName not in deviceSet and existDevice.state != device_actor.CONS.STATE_UNLINE:
                    logging.info("发现设备掉线")
                    device_manager.unlineDeviceActor(existDeviceName)

#            print([str(x) for x in list(existDeviceMap.values())])

        except Exception as e:
            print(e)
        time.sleep(2)

    device_manager.release()
